#pragma once

#include <iostream>
#include <pthread.h>
#include <string>

namespace Thread
{

    class ThreadData
    {
    public:
        ThreadData(const std::string& name, pthread_mutex_t* lock)
            :_name(name), _lock(lock)
        {}
    public:
        std::string _name;
        pthread_mutex_t* _lock;
    };
    
    typedef void* (*func_t)(ThreadData* td);

    class thread
    {
        static void* ThreadRoutine(void* args)
        {
            thread* self = static_cast<thread*>(args); // 获取this指针
            self->Excute();
            return nullptr;
        }

        void Excute()
        {
            std::cout << _name << " is running" << std::endl;
            _isRunning = true;
            _func(_td);
            _isRunning = false;
        }

    public:
        thread(const std::string& name, func_t func, ThreadData* td): _name(name), _func(func), _td(td)
        {
            std::cout << "create " << name << " done" << std::endl;
        }
        ~thread()
        {}
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if (n != 0) return false;
            return true;
        }
        void Stop()
        {
            if (_isRunning)
            {
                pthread_cancel(_tid);
                _isRunning = false;
                std::cout << _name << " Stop" << std::endl;
            }
        }
        void Join()
        {
            pthread_join(_tid, nullptr);
            std::cout << _name << " Joined" << std::endl;
        }
    private:
        std::string _name; // 线程名
        func_t _func; // 回调函数
        pthread_t _tid; // 线程id
        bool _isRunning; // 线程状态
        ThreadData* _td;
    };
}